<template>
  <div class="class-manager">
    <!-- 添加班级区域 -->
    <div class="class-operations">
      <el-button type="primary" @click="showAddDialog">添加资源分类</el-button>
    </div>

    <!-- 班级列表 -->
    <el-table
        ref="classTable"
        :data="classes"
        style="width: 100%"
        row-key="id"

    >

      <el-table-column prop="resourceType" label="资源分类名称"></el-table-column>

      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="danger"
              @click.stop="deleteClass(scope.row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 添加班级对话框 -->
    <el-dialog
        title="添加资源分类"
        :visible.sync="addDialogVisible"
        width="30%"
    >
      <el-form :model="newClass" label-width="80px">
        <el-form-item label="资源分类名称">
          <el-input v-model="newClass.name" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addClass">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {

      classes: [],
      addDialogVisible: false,
      newClass: {
        name: "",
      },
      nextClassId: 3
    };
  },
  created() {
    this.loadClasses()
  },
  methods: {
    async loadClasses() {
      try {
        const response = await this.$request.get('/project/selectResourcesType');

        // 初始化班级数据，添加加载状态
        this.classes = response.data

      } catch (error) {
        console.error('获取班级列表失败:', error);
      }
    },


    // 显示添加对话框
    showAddDialog() {
      this.addDialogVisible = true;
      this.newClass.name = "";
    },

    // 添加新班级
    async addClass() {
      try {
        const res = await this.$request.post(`/admin/addResourceType?resourceType=${encodeURIComponent(this.newClass.name)}`);


        // 2. 添加成功处理
        this.$message.success('分类添加成功！');
        this.newClass = '';


        // 4. 刷新当前项目数据
        await this.loadClasses();
      } catch (error) {
        this.$message.error('添加分类失败');
      }
    },

    // 删除班级
    async deleteClass(id) {
      try {
        await this.$request.post(`/admin/removeResourceType?id=${encodeURIComponent(id)}`);
        this.$message.success('分类删除成功！');
        // 4. 刷新当前项目数据
        await this.loadClasses();
      } catch (error) {
        this.$message.error('删除失败');
      }
    },


  }
};
</script>

<style scoped>
.class-manager {
  padding: 20px;
}

.class-operations {
  margin-bottom: 20px;
}


</style>